package Reflection;

import java.lang.reflect.Method;

public class demo12 {
    public static void main(String[] args) throws Exception {
        //先获取class对象
        Class c = Cat.class;

        //Cat对象
        Cat cat = new Cat();
        //再来获取指定的方法来设置名字,年龄
        Method setNameMethod = c.getDeclaredMethod("setName", String.class);
        setNameMethod.setAccessible(true);
        setNameMethod.invoke(cat,"小板");

        Method setAgeMethod = c.getDeclaredMethod("setAge", int.class);
        setNameMethod.setAccessible(true);
        setAgeMethod.invoke(cat,2);

        //查看是否设置成功
        Method getNameMethod = c.getDeclaredMethod("getName");
        getNameMethod.setAccessible(true);
        String name = (String) getNameMethod.invoke(cat);
        System.out.println(name);

        Method getAgeMethod = c.getDeclaredMethod("getAge");
        getAgeMethod.setAccessible(true);
        int age = (int) getAgeMethod.invoke(cat);
        System.out.println(age);

        System.out.println(cat);
    }
}
